package com.Shoping.filter;

import com.Shoping.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 测试期间先注释，没问题之后将注释摘掉
 */

//@WebFilter(filterName = "login", urlPatterns = "/*.do")

public class ApiFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("loginFilter.init");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("loginFilter.doFilter");

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String servletPath = httpServletRequest.getServletPath();
        System.out.println("servletPath = " + servletPath);
        String method = httpServletRequest.getParameter("method");
        System.out.println("method = " + method);

        /**
         * 此处需要后期修改文件名
         */
        if (servletPath.equals("/login.jsp") ||
                (servletPath.equals("/user") && method.equals("login"))
                || servletPath.equals("/fail.jsp")){
            chain.doFilter(request,response);
            return;
        }
        //--------------------------------------------------------------------------------

        HttpSession httpSession = httpServletRequest.getSession();
        User user = (User) httpSession.getAttribute("user");
        System.out.println("user = " + user);

        /**
         * 此处也需要修改
         */
        if (user == null){
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
            return;
        }
        //----------------------------------------------------------------------------------------

        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        System.out.println("loginFilter.destroy");
    }

}
